<?php
require_once ('SendMail.php');
require_once ('Config/config.php');

//require_once ('ref/GetLoginInfo.php');

//$date = new DateTime(); var_dump($date); die();
/*
$date = '2013/06/18 05:12:12';
$dddd = date("Y/m/t h:i:s", strtotime($date));
var_dump(strtotime($dddd));
die();
	
$a = array('000' => array('a1' => '1', 'a1' => '2', 'a1' => '3'));
$a['a'] = array('a1' => '1', 'a1' => '2', 'a1' => '3');
$a['b'] = array('b1' => '2');
$a['c'] = array('b2' => '3');
var_dump($a['b']['b1']);
die();
*/

class SendMailAction {
	public function __construct() {
	}
	
	public function sendContactMail($request, $to = null, $BCC = null) {
		$nameContact = null;
		$emailContact = null;
		$phoneContact = null;
		$companyContact = null;
		$msgContact = null;

		if (isset($request['newsletter']) && trim($request['newsletter']) !== '') {
			$this->sendJoinMail($request);
			return;
		}
		
		if (isset($request['nameContactId']) && trim($request['nameContactId']) !== '') {
			$nameContact = $request['nameContactId'];
		}
		
		if (isset($request['emailContactId']) && trim($request['emailContactId']) !== '') {
			$emailContact = $request['emailContactId'];
		}
		
		if (isset($request['phoneContactId']) && trim($request['phoneContactId']) !== '') {
			$phoneContact = $request['phoneContactId'];
		}
		
		if (isset($request['companyContactId']) && trim($request['companyContactId']) !== '') {
			$companyContact = $request['companyContactId'];
		}
		
		if (isset($request['msgContactId']) && trim($request['msgContactId']) !== '') {
			$msgContact = $request['msgContactId'];
		}

		$staffId      		  = '-1';
		$failSendMailErrMsg	  = "Send mail Error";		
		
		// mail info
		$sendMailFlag = false;
		$smtpHost 	  = SMTP_HOST;
		$smtpPort 	  = SMTP_PORT;
		$smtpSSL 	  = SMTP_SSL;
		$smtpUsername = SMTP_USER;
		$smtpPassword = SMTP_PASS;
		$arrSMTPConfg = array(
							  'host' => $smtpHost,
							  'port' => $smtpPort,
							  //'auth' => 'login',
							  'ssl' => $smtpSSL,
							  'username' => $smtpUsername,
							  'password' => $smtpPassword);					  
		
		try {	
			$from               = $emailContact;		
			$nameParam 			= $companyContact;
			$greetingParam		= $nameContact;		
			$commentParam 		= $msgContact;	
			$contactTargetParam = $phoneContact;
			$mailAddrParam 		= $emailContact;
			$urlParam 			= 'https://10.100.100.51/webapp/modules/cbentry/?token=gvbp1UyKfGb&key=true';
			
			$from 				= $from != null ? $from : MAIL_FROM;
			$to 				= $to != null ? $to : 'manhhieu20042000@yahoo.com';//'manhhieu20042000@yahoo.com';'hieunm@allexceed.co.jp';
			$subject 			= "";
			$content 			= "";
			$body 				= $this->getContentMail();
			$lines  			= explode("\n", $body);
			
			for ($i = 0; $i < count($lines); $i++) { 
				$arr  = explode(":", $lines[$i]);
				if ($arr[0] === 'Subject') {
					$subject = trim($arr[1]);
					//break;
				}
				
				if ($i >0) {
						$content .= $lines[$i] . "\n";
					}
			}
			
			if ($body != NULL) {
				$keys = array("{\$nameParam}", "{\$greetingParam}", "{\$mailAddrParam}", 
							  "{\$commentParam}", "{\$urlParam}", "{\$contactTargetParam}");
				$strReplace = array(
						$nameParam,
						$greetingParam,
						$mailAddrParam,
						$commentParam,
						$urlParam,
						$contactTargetParam);
				$content = str_replace($keys, $strReplace, $content);
			}
			
			// Call Class for send mail
			$senMailClass = new SendMail();
			$sendMailFlag = $senMailClass->sendMail($from, $to, $subject, $content);
			
			/*
			//attach file
			$filePath = realpath(dirname(__FILE__)) . "/abc.pdf";
			$fileName = "キャッシュバックお申込書.pdf";
			
			if (!file_exists($filePath)) {
				echo "file not exist";
				return;
			}
		
			// Call Class for send mail
			$senMailClass = new SendMail();
			$sendMailFlag = $senMailClass->sendMailAttachFilePdf($to, $subject, $content, $filePath, $fileName);
			*/			
			
			/*
			// starting word 
			$word = new COM("word.application") or die("Unable to instanciate Word"); 
			echo "Loaded Word, version {$word->Version}\n"; 
		
			// bring it to front 
			$word->Visible = 1; 
			// Open a word document, or anything else that word 
			// can read 
			$input ="c:\\test.html"; 
			$word->Documents->Open($input); 
			//$word->Documents->SaveAs("some_tst.doc"); 
			$word->quit(); 
			*/		
			
			// set errMsg when send mail fail
			$errorMessage = $failSendMailErrMsg;		
			// Insert table DDBMailKey when send mail success
			if ($sendMailFlag == true) {
				echo 'send mail success ......';
			} else {
				$this->errorMessage($errorMessage);
				return;
			}	
		} catch (Exception $e) {
			echo json_encode(array("success" => false,"error" => $e->getMessage()));
		}
	}
	
	public function sendJoinMail($request, $to = null, $BCC = null) {
		$emailContact = null;

		if (isset($request['newsletter']) && trim($request['newsletter']) !== '') {
			$emailContact = $request['newsletter'];
		}

		$staffId      		  = '-1';
		$failSendMailErrMsg	  = "Send mail Error";		
		
		// mail info
		$sendMailFlag = false;
		$smtpHost 	  = SMTP_HOST;
		$smtpPort 	  = SMTP_PORT;
		$smtpSSL 	  = SMTP_SSL;
		$smtpUsername = SMTP_USER;
		$smtpPassword = SMTP_PASS;
		$arrSMTPConfg = array(
							  'host' => $smtpHost,
							  'port' => $smtpPort,
							  //'auth' => 'login',
							  'ssl' => $smtpSSL,
							  'username' => $smtpUsername,
							  'password' => $smtpPassword);					  
		
		try {				
			$from 				= 'manhhieu20042000@yahoo.com';	
			$to 				= $emailContact;
			$subject 			= "Gui Bao Gia";
			$content 			= "Gui Bao Gia San Pham";
					
			//attach file
			//$filePath = realpath(dirname(__FILE__)) . "/abc.pdf";
			//$fileName = "キャッシュバックお申込書.pdf";
			$filePath = REPORT_FOLDER_URL . "/abc.pdf";
			$fileName = "キャッシュバックお申込書.pdf";
			
			if (!file_exists($filePath)) {
				echo "file not exist " . $filePath;
				return;
			}

			// Call Class for send mail
			$senMailClass = new SendMail();
			$sendMailFlag = $senMailClass->sendMailAttachFilePdf($to, $subject, $content, $filePath, $fileName);
				
			
			/*
			// starting word 
			$word = new COM("word.application") or die("Unable to instanciate Word"); 
			echo "Loaded Word, version {$word->Version}\n"; 
		
			// bring it to front 
			$word->Visible = 1; 
			// Open a word document, or anything else that word 
			// can read 
			$input ="c:\\test.html"; 
			$word->Documents->Open($input); 
			//$word->Documents->SaveAs("some_tst.doc"); 
			$word->quit(); 
			*/	
			
			// set errMsg when send mail fail
			$errorMessage = $failSendMailErrMsg;		
			// Insert table DDBMailKey when send mail success
			if ($sendMailFlag == true) {
				echo 'send mail success ......';
			} else {
				$this->errorMessage($errorMessage);
				return;
			}	
		} catch (Exception $e) {
			echo json_encode(array("success" => false,"error" => $e->getMessage()));
		}
	}

	/**
	 * Get errorMessage
	 */
	private function errorMessage ($errorMessage = '') {
		echo json_encode(array("success" => false,"error" => $errorMessage));
	}
	
	/**
	 * Get Content Mail
	 * @param null
	 * @return String $content
	 */
	private function getContentMail() {
	    $urlFile = MAIL_TEMPLATE_FILE_PATH;
		
	    $isFileExist = file_exists($urlFile);
	
	    if ($isFileExist) {
	        $content = file_get_contents($urlFile);
	
	        return $content;
	    }
	
	    return NULL;
	}
	
}

//$sending = new SendMailAction(); $sending->sendContactMail($_REQUEST);
